package com.dk.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dk.entity.DtFans;
import com.dk.entity.DtItem;
import com.dk.mapper.DtFansMapper;
import com.dk.mapper.DtItemMapper;
import com.dk.service.IDtFansService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dk.vo.DtItemVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2021-12-20
 */
@Service
public class DtFansServiceImpl extends ServiceImpl<DtFansMapper, DtFans> implements IDtFansService {
    @Resource
    private DtFansMapper fansMapper;
    @Resource
    private DtItemMapper itemMapper;

    @Override
    public  List<DtItemVO> selectByConcern(Integer uid, Integer pageNumber, Integer pageSize) {
        //第一种方式
        //QueryWrapper<DtFans> uid1 = Wrappers.<DtFans>query().eq("uid", uid);
        // List<DtFans> dtFans1 = fansMapper.selectList(uid1);
        //根据UID查询粉丝表中所有被我关注过的用户id
        Map<String,Object> map = new HashMap();
        Map<String,Object> map2 = new HashMap();
        map.put("uid",uid);
        //第二种方式
        List<DtFans> dtFans = fansMapper.selectByMap(map);
        for (DtFans s : dtFans) {
            map2.put("sellerid", s.getFollowId());
        }
        //不分页
        //根据查询出来的粉丝表的follow_id (也就是商家id) 对应dt_item表中的sellerid字段 并进行分页查询和时间最新查询
        List<DtItem> dtItems = itemMapper.selectByMap(map2);
        List<DtItemVO> itemDTOList = dtItems.stream().map(fan -> {
            DtItemVO dtItemVo = new DtItemVO();
            BeanUtils.copyProperties(fan, dtItemVo);
            return dtItemVo;
        }).collect(Collectors.toList());
        //分页
        // 根据粉丝表查询出来的follow_id (也就是商家id) 去查询dt_item表中的sellerid字段 并进行分页查询和时间最新查询
        Page<DtItem> page = new Page<>(pageNumber,pageSize);
        QueryWrapper<DtItem> queryWrapper = new QueryWrapper<>();
        List<Integer> list = dtFans.stream().map(s -> Integer.parseInt(s.getFollowId().toString())).collect(Collectors.toList());
        queryWrapper.in("sellerid",list);
        IPage<DtItem> dtItemIPage = itemMapper.selectPage(page, queryWrapper);
        List<DtItem> records = dtItemIPage.getRecords();
        List<DtItemVO> dtItemVos = JSONObject.parseArray(JSONObject.toJSONString(records), DtItemVO.class);
        return dtItemVos;
    }
}
